<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .a {
            width: 30px;
            height: 30px;
            background-color: #f00;
            position: absolute;
            border-radius: 50%;
        }
    </style>
</head>

<body>

    <div class="a"></div>

    <script>

        // 生成20个div
        for (var i = 0; i < 20; i++) {
            var oDiv = document.createElement('div');
            // oDiv.innerHTML = i + 1;
            oDiv.className = 'a';
            document.body.appendChild(oDiv);
        }


        var oDivs = document.querySelectorAll('.a');



        var t;

        document.onkeydown = function (e) {
            var e = e || event;
            // console.log(e.keyCode);   // 38 40  37  39

            clearInterval(t);  // undefined

            t = setInterval(function () {

                var x = oDivs[0].offsetLeft;
                var y = oDivs[0].offsetTop;

                if (e.keyCode === 38) {
                    y-=25;
                }
                else if (e.keyCode === 40) {
                    y+=25;
                }
                else if (e.keyCode === 37) {
                    x-=25;
                }
                else if (e.keyCode === 39) {
                    x+=25;
                }

                // 反着写
                for (var i = oDivs.length - 1; i > 0; i--) {
                    oDivs[i].style.left = oDivs[i - 1].style.left;
                    oDivs[i].style.top = oDivs[i - 1].style.top;
                }

                // 第一个跟着鼠标
                oDivs[0].style.left = x + 'px';
                oDivs[0].style.top = y + 'px';


            }, 100)
        }



    </script>
</body>

</html>